<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<%@ taglib prefix="memberForm" uri="http://www.tongxingzhe.cn/memberForm" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${activity == null ? '发布' : '编辑'}活动</title>
    <%@include file="../include/commonFile.jsp" %>
    <script src="//api.map.baidu.com/api?v=2.0&ak=2izIwlMmDVH737ms8m4Y8uHsoxtEIR65"></script>
    <link rel="stylesheet" href="${ctx}/css/common/form.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_act.css">
    <style TYPE="text/css">
        .form-tip {
            float: left;
            margin-right: 10px;
            width: calc(100% - 110px);
        }

        .add-form-content .form-inner {
            padding: 10px;
        }

        .border {
            border: 1px solid #eee;
            padding-left: 0px;
            padding-right: 0px;
            border-radius: 4px;
        }

        fieldset legend {
            font-size: 18px;
            margin-left: 30px;
        }
    </style>
</head>
<body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/activity/activity/save.do">
                    <input type="hidden" name="member" value="${activity.member}">
                    <div class="preview-box">
                        <div class="top-tip">
                            <span class="tip-inner"><span class="tip-title">效果预览</span></span>
                        </div>
                        <a class="preview-btn layui-btn layui-btn-danger layui-btn-sm" href="javascript:void(0)"
                           lay-submit lay-filter="*"><i class="iconfont icon-refresh btn-icon"></i>预览</a>
                        <iframe style="width: 360px;height: 760px;"
                                src="${ctx}/phone/preview.do?url=/micWeb/html/hd/hd_preview.html?id=${activity.id}"
                                frameborder="0"></iframe>
                    </div>

                    <div class="form-outer">
                        <input type="hidden" lay-verify="groupIsExpire" />
                        <fieldset class="border mb10">
                            <legend>活动基本信息</legend>
                            <div class="form-inner">
                                <c:if test="${fn:length(childrens) > 0}">
                                    <div class="layui-form-item">
                                        <div class="layui-inline">
                                            <label class="layui-form-label">子账号</label>
                                            <div class="layui-input-inline">
                                                <select name="childrenId">
                                                    <option value="">请选择</option>
                                                    <c:forEach var="children" items="${childrens}">
                                                        <option value="${children.id}" ${children.id == activity.member ? 'selected="selected"' : ""}>${children.realname}</option>
                                                    </c:forEach>
                                                </select>
                                            </div>
                                            <div class="layui-form-mid layui-word-aux">如果选择了子账号，则表示代替子账号发布数据,活动下有报名人,不能修改</div>
                                        </div>
                                    </div>
                                </c:if>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">活动标题<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block ">
                                        <input type="text" name="title" lay-verify="title" placeholder="活动标题"
                                               class="layui-input form-tip" maxlength="50"
                                               value="${activity.title}" style="width: 50%"/>
                                        <input type="hidden" name="id" value="${activity.id}"/>
                                        <input type="hidden" name="isCrowdfunded" value="0"/>
                                        <input type="hidden" name="privilegeCode" value="activity_publish"/>
                                        <div class="layui-form-mid layui-word-aux">最多50字符</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">海报<span class="f-verify-red">*</span></label>
                                    <div class="cover-content">
                                        <input type="hidden" name="pic" id="pic" lay-verify="pic" value="${activity.pic}"/>
                                        <c:if test="${activity == null || empty activity.pic}">
                                        <span id="cover-img" class="cover-img"
                                              style="background-image:url(${ctx}/image/posterImg.png)"></span>
                                        </c:if>
                                        <c:if test="${activity != null && not empty activity.pic}">
                                        <span id="cover-img" class="cover-img"
                                              style="background-image:url('${activity.pic}')"></span>
                                        </c:if>
                                        <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加海报</a>
                                        <div class="form-word-aux">建议尺寸：800x450</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">报名截止时间<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <input class="layui-input" name="endDate" lay-verify="endDate" placeholder="报名截止时间"
                                               id="endTime" style="width: 190px; float: left; margin-right: 10px;" readonly
                                               value='<fmt:formatDate value="${activity.endTime}" pattern="yyyy-MM-dd HH:mm" />'/>
                                        <div class="layui-form-mid layui-word-aux">请选择报名截止时间</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">活动开始时间<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <input class="layui-input" name="startDate" lay-verify="startDate"
                                               placeholder="活动开始时间"
                                               id="startTime" style="width: 190px; float: left; margin-right: 10px;" readonly
                                               value='<fmt:formatDate value="${activity.startTime}" pattern="yyyy-MM-dd HH:mm" />'/>
                                        <%--<div class="layui-form-mid layui-word-aux">活动开始时间不能早于报名截止</div>--%>
                                    </div>
                                </div>
                                <%@include file="cityAreaMapNew.jsp" %>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">报名费用<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <%@include file="../include/counterfoil.jsp" %>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">隐藏报名人员<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <div class="layui-input-inline">
                                            <input type="radio" name="joinHidden" value="1"
                                                   title="是" ${activity == null || activity.joinHidden == 1 ? 'checked="checked"' : ''}>
                                            <input type="radio" name="joinHidden" value="0"
                                                   title="否" ${activity != null && activity.joinHidden == 0 ? 'checked="checked"' : ''}>
                                        </div>
                                        <div class="dib calc-350">
                                            <a class="red tip-link"
                                               href="javascript:openHiddenShow('手机效果展示图', '#hidden_show_plane')">
                                                <i class="iconfont icon-piclight"></i>效果展示图</a>
                                            <p class="gray">说明:在前期活动数据较少时，适当使用隐藏数据功能，可以避免推广的尴尬，等数据较多时可再调整</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">活动描述</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="remarks" placeholder="活动描述" class="layui-input" maxlength="100"
                                               value="${activity.remarks}">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">活动详情<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-block">
                                        <script id="ueditor1" type="text/plain"></script>
                                        <div style="display: none" id="contentView">${activityDetail.content}</div>
                                        <input type="hidden" name="content" id="content" lay-verify="content"
                                               data-link-ue="ueditor1"/>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>活动报名表单</legend>
                            <div class="form-inner">
                                <%@include file="../gatherForm/activityCreateForm.jsp"%>
                                <div class="cl"></div>
                            </div>
                        </fieldset>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                                <a href="${ctx}/activity/activity/activityList.do" class="layui-btn layui-btn-primary">取消</a>
                            </div>
                        </div>
                    </div>
                    <div>
                        <input type="hidden" name="costCache" />
                        <input type="hidden" name="formItemCache" />
                    </div>
                </form>
            </div>
        </div>
        <!--底部-->
        <%@include file="../include/footer.jsp" %>
        <div style="display: none" id="create_date_str">
            <fmt:formatDate value="${activity.createDate}" pattern="yyyy-MM-dd HH:mm:ss"/>
        </div>
        <c:set var="expirationTime" value="${memberForm:getExpirationTimeById(sessionScope.newCurrentUser.id)}"/>
        <c:set var="isExpire" value="${memberForm:isExpire(sessionScope.newCurrentUser.id, null)}"/>
    </section>
    <div id="hidden_show_plane" class="pt15" style="display: none;">
        <div class="dib l" style="width: 50%;">
            <div class="pt10 pb10" style="border-right: 1px solid #7f7f7f;">
                <div class="show-img"
                     style="background-image: url(../../image/dialog/hide_2.png);"></div>
            </div>
            <p class="mt10 f18 tc">（隐藏报名人员）</p>
        </div>
        <div class="dib l" style="width: 50%;">
            <div class="pt10 pb10">
                <div class="show-img"
                     style="background-image: url(../../image/dialog/hide_1.png);"></div>
            </div>
            <p class="mt10 f18 tc">（显示报名人员）</p>
        </div>
    </div>
</div>


<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.config.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.all.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadCI.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadVideo.js"></script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" src="${ctxStatic}/UEditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="${ctx}/script/common/form_cache.js"></script>

<script>
    var ue = UE.getEditor('ueditor1', {
        initialFrameWidth : 700,
        initialFrameHeight: 500
    });
    var form, formcache;
    txz.initHeader({
        nav: [{
            name: '活动管理',
            href: '${ctx}/activity/activity/activityList.do'
        }, {
            name: '${activity == null ? '发布' : '编辑'}活动',
            curr: true
        }],
        btns: [{
            type: 'back'
        }]
    });
    $(function () {

        layui.use(['form', 'laydate', 'element'], function () {
            form = layui.form, laydate = layui.laydate;
            var radioValue = null;
            var element = layui.element;
            form.on('radio(isFree)', function (data) {
                radioValue = data.value;
                if (radioValue == "noFree") {
                    $("[name=price]").prop("disabled", false);
                } else {
                    $("[name=price]").val("");
                    $("[name=price]").prop("disabled", true);
                }
            });
            //自定义验证规则
            form.verify({
                groupIsExpire: function() {
                    if ('${isExpire}' == 'true') {
                        txz.openExpireDialog();
                        return false;
                    }
                    return "";
                },
                title: function (value) {
                    if (value == "") {
                        return '请填写活动标题';
                    }
                },
                pic: function (value) {
                    if (value == "") {
                        return "请上传活动海报";
                    }
                },
                endDate: function (value) {
                    if (value == "") {
                        return "请设置报名截止时间";
                    }

                    if (util.getTimeMillis(value) < util.getTimeMillis()) {
                        return "报名截止时间不得早于当前时间";
                    }

                    var max = '${memberForm:dateFormat(expirationTime, 'yyyy-MM-dd HH:mm:ss')}';
                    if (value >= max) {
                        return "截止时间不能超过账户过期时间";
                    }
                },
                startDate: function (value) {
                    if (value == "") {
                        return "请设置活动开始时间";
                    }

/*                    var endDate = $("[name=endDate]").val();
                    if (endDate >= value) {
                        return "活动开始时间不能早于报名截止时间";
                    }*/

                    if (util.getTimeMillis(value) < util.getTimeMillis()) {
                        return "活动开始时间不得早于当前时间";
                    }
                },
                place: function (value) {
                    if (value == "") {
                        return "请设置活动场所";
                    }
                },
                area_select: function (value) {
                    var display = $("#areaInput").css("display");
                    if (value == "" && display == "none") {
                        return "请设置活动区域";
                    }
                },
                area_input: function (value) {
                    var display = $("#areaInput").css("display");
                    if (value == "" && display == "block") {
                        return "请设置活动区域";
                    }
                },
                city: function (value) {
                    if (value == "") {
                        return "请选择活动举办的城市";
                    }
                },
                // 	       	lat : function(value){
                // 	       		if(value == ""){
                // 	       			return "请选择一个活动场所"
                // 	       		}
                // 	       	},
                // 	        activityType : function (value) {
                // 	        	if (value == ""){
                // 	        		return "请设置活动类型";
                // 	        	}
                // 	        },
                limitNum: function (value) {
                    if (value == "") {
                        return "请设置活动人数上限";
                    } else if (!util.checkNumber(value)) {
                        return "请输入正确的金额";
                    } else if (parseInt(value) == 0) {
                        return "请输入大于0的数字";
                    }
                },
                price: function (value) {
                    if (radioValue == null) {
                        var type = $("[name=isFree]:checked").val();
                        if (type == "noFree") {
                            if (value == "") {
                                return "请设置活动报名金额";
                            } else if (!util.checkFloat(value)) {
                                return "请输入正确的金额";
                            }
                        }
                    } else {
                        if (radioValue == "noFree") {
                            if (value == "") {
                                return "请设置活动报名金额";
                            } else if (!util.checkFloat(value)) {
                                return "请输入正确的金额";
                            }
                        }
                    }
                },
                content: function (value) {
                    $("#contentView").html(ue.getContent());
                    var content = $("#contentView").html();
                    if (content == "") {
                        return "请填写活动详情";
                    }
                }
            });
            //监听提交
            form.on('submit', function (data) {
                if (checkCost() && checkField()) {
                    submitForm(data);
                }
            });

            form.render('radio');
            form.render('checkbox');
            form.render('select');

            var min;
            if (${empty activity.id}) {
                min = new Date().Format('yyyy-MM-dd HH:mm:ss');
            } else {
                min = $("#create_date_str").text();
            }

            var max = '${memberForm:dateFormat(expirationTime, 'yyyy-MM-dd HH:mm:ss')}';

            //日期
            var start = {
                elem: '#startTime',
                min: min,
                max: '2099-06-16 23:59',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm'
            };

            var end = {
                elem: '#endTime',
                min: min,
                max: max || '2099-06-16 23:59',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm' //日期格式
            };
            laydate.render(start);
            laydate.render(end);

            //初始化地图控件
            txz.Map.init({
                layForm: form,
                data: {
                    cityId: '${activity.cityId}',
                    areaInput: '${activity.area}',
                    place: '${activity.place}',
                    cityName: '${cityName}',
                    lat: '${activity.lat}',
                    lng: '${activity.lng}'
                }
            });
        });
        txz.saveStatus = false;

        ue.addListener('ready', function () {
            this.setHeight(500);
            if ($("#contentView").html() != "") {
                this.setHeight(850);
            }
            this.setContent($("#contentView").html());
            //等待ueditor加载完后加载缓存
            if (!'${activity.id}') { //新增时使用
                formcache = new fCache({
                    fCacheKey: 'form_cache_act',//暂存的key
                    cacheCallback: loadCacheData,//获取到缓存后加载的方法
                    getFormData: getFormData //获取缓存数据的方法
                }).init();
            }
        });
        ue.addListener('blur', function () {
            $("#contentView").html(ue.getContent());
        });

        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x450',
                type: '<%=TargetType.ACTIVITY.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
    })

    function getFormData() {
        $("#content").val(ue.getContent().replace(/&quot;/gi, ""));

        // 票据
        var _costArray = new Array();
        $(".cost_container").find(".cost-item-new").each(function (index, ele) {
            var map = {
                number: index + 1,
                index: index,
                type: $(ele).find(".cost_type").find("option:selected").val(),
                name: $(ele).find(".cost_name").val() || '',
                payment: $(ele).find(".cost_payment").val() || '',
                limitNum: $(ele).find(".cost_limitNum").val() || '',
                remarks: $(ele).find(".cost_remarks").val() || ''
            };
            _costArray.push(map);
        });
        $("[name=costCache]").val(JSON.stringify(_costArray));

        // 信息收集表单
        var _formItemArray = new Array();
        $("#event_template_form_items").find(".form-item-nn").each(function (index, ele) {
            var _childArray = new Array();
            $(ele).find(".event-create-sign-select").find(".sub-item").each(function (j, cEle) {
                var map = {
                    j : j,
                    id : $(cEle).find(".subitem-id").val() || '',
                    sort : $(cEle).find(".subitem-sort").val() || '',
                    name : $(cEle).find(".subitem-name").val() || ''
                };
                _childArray.push(map);
            });

            var map = {
                index : index,
                tmpItem : {
                    required : $(ele).find("[type=checkbox]").prop("checked"),
                    id : $(ele).find(".item-id").val() || '',
                    Type : $(ele).find(".item-type").val() || '',
                    Sort : !util.isValid($(ele).find(".item-sort")) ? '' : $(ele).find(".item-sort").val() || '',
                    Category : $(ele).find(".item-category").val() || '',
                    Title : $(ele).find(".item-title").val() || '',
                    Description : $(ele).find(".item-description").val() || '',
                    Subitems : _childArray
                }
            };
            _formItemArray.push(map);
        });
        $("[name=formItemCache]").val(JSON.stringify(_formItemArray));

        var formData = util.serializeForm($('#myForm').serializeArray());
        return formData;
    }

    //保存表单
    function submitForm(data) {
        txz.submitObject(data.elem, function (callBack) {
            resetIndex();
            resetFormIndex();
            var action = $("#myForm").attr("action");
            var formData = getFormData();
            txz.ajaxRequest({
                method: 'post',
                url: action,
                saveCache: true,
                cacheObj: formcache,
                params: formData,
                callBack: function (res) {
                    typeof callBack === 'function' && callBack();
                    if (res.success) {
                        if ($(data.elem).hasClass('preview-btn')) {
                            if ('${empty activity.id}' === 'true') {
                                location.href = '${ctx}/activity/activity/publishAct.do?id=' + res.data;
                            } else {
                                var $previewFrame = $($('.preview-box').find('iframe')[0].contentWindow.document).find('iframe');
                                $previewFrame.attr('src', $previewFrame.attr('src'));
                            }
                        }
                        else {
                            util.layerMsgSuccess("提交成功", function () {
                                location.href = "${ctx}/activity/activity/activityList.do";
                            });
                        }
                    } else {
                        util.layerMsgError(res.description)
                    }
                },
                errorBack: function (xhr, type) {
                    if (xhr.status == 402) {
                        util.layerMsgError(xhr.responseText);
                    } else if (xhr.status == 500) {
                        util.layerMsgError("提交失败")
                    }
                }
            })
        });
        return false;
    }

    //此方法用于加载缓存数据
    function loadCacheData(cacheData) {
        //是否收费
        if (cacheData['isFree']) {
            radioValue = cacheData['isFree'];
            if (radioValue == "noFree") {
                $("[name=price]").prop("disabled", false);
            } else {
                $("[name=price]").val("");
                $("[name=price]").prop("disabled", true);
            }
        }
        //加载封面图
        if (cacheData['pic']) {
            $('#cover-img').css('background-image', 'url(' + cacheData['pic'] + ')');
        }
        form.render();
        txz.Map.init({
            layForm: form,
            data: {
                cityId: cacheData.cityId,
                areaInput: cacheData.areaSelect || cacheData.areaInput,
                place: cacheData.place,
                lat: cacheData.lat,
                lng: cacheData.lng
            }
        });

        // 票据
        if (cacheData['costCache']) {
            var costCache = JSON.parse(cacheData['costCache']);
            if (costCache.length > 0) {
                loadCounterfoil(costCache);
            }
        }

        // 信息收集表单
        if (cacheData['formItemCache']) {
            var formItemCache = JSON.parse(cacheData['formItemCache']);
            if (formItemCache.length > 0) {
                loadFormItem(formItemCache);
            }
        }
    }
    //效果展示图
    function openHiddenShow(title, container) {
        /*txz.openHelpDialog({
         title: '手机效果预览',
         describe: '',
         detailList: [{
         text: '不隐藏报名人员',
         url: '/image/dialog/hide_1.png'
         }, {
         text: '隐藏报名人员',
         url: '/image/dialog/hide_2.png'
         }]
         })*/

        var index = layer.open({
            type: 1,
            area: ['800px', '700px'],
            title: [title, 'text-align:center;'],
            shade: 0.6,
            shadeClose: true,
            content: $(container)
        });
    }

    // 文本编辑器图片上传
    function uEditorUploadCI(editor) {
        txz.openSelImg({
            min: 1,
            type: '<%=TargetType.ACTIVITY.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function uEditorUploadCIVideo(editor) {
        txz.openSelVideo({
            min: 1,
            type: '<%=TargetType.ACTIVITY.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }
</script>
</body>
</html>